<template>
  <div>
    <el-button type="primary" @click="openAdd">添加围栏</el-button>

    <div
        v-for="f in fences"
        :key="f.fenceId"
        class="fence-item"
    >
      <div>{{ f.fenceName }} - 半径 {{ f.radius }} 米</div>
      <div>{{ f.name }} - {{ f.out ? '越界' : '正常' }}</div>
      <el-button size="small" @click="edit(f)">编辑</el-button>
      <el-button size="small" type="danger" @click="del(f.fenceId)">删除</el-button>
    </div>

    <!-- 围栏表单弹窗 -->
    <el-dialog
        v-model="showForm"
        :title="form.id ? '编辑围栏' : '新增围栏'"
        width="90%"
        @opened="onDialogOpened"
        @closed="onDialogClosed"
    >
      <el-form :model="form" label-width="80">
        <el-form-item label="搜索位置"><SearchBox @select="onSearchSelect" />
        </el-form-item>
      </el-form>

      <el-form :model="form" label-width="80">
        <el-form-item label="名称">
          <el-input v-model="form.fenceName" />
        </el-form-item>
        <el-form-item label="半径(m)">
          <el-input-number v-model="form.radius" :min="50" :max="2000" />
        </el-form-item>
      </el-form>
      <div id="mini-map" style="width:100%;height:300px" />
      <template #footer>
        <el-button @click="showForm=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick, watch, computed,inject} from 'vue'
import { loadBMap } from '@/utils/bmap-loader'
import { addFence,getFencesByElderly ,updateFence, deleteFence, } from '@/api/fence'
import SearchBox from './SearchBox.vue'
import {ElMessage} from "element-plus";
import { initBMap } from '@/utils/init-bmap';
import { gpsToBaidu } from '@/utils/coord-transform';
import axios from "axios";

let miniMap = null
let miniCircle = null
const BASE_URL = 'http://localhost:8080'
const emit = defineEmits(['update:visible'])

// 读取登录用户 id
const familyUserId = computed(() => {
  const u = JSON.parse(localStorage.getItem('user') || '{}')
  return u.id ?? u.userId
})

/* -------------------- 围栏列表 -------------------- */
const fences = ref([])
const showForm = ref(false)
const form = ref({})
const user = JSON.parse(localStorage.getItem('user') || '{}');
const currentElderlyId = inject('currentElderlyId')
const localElderlyId = ref(currentElderlyId?.value || null)

const openAdd = () => {
  form.value = { fenceName: '新围栏', radius: 300 }
  showForm.value = true
}
const edit = (row) => {
  form.value = { ...row }
  form.value.lng = row.centerLongitude
  form.value.lat = row.centerLatitude
  showForm.value = true
}

const onDialogOpened = async () => {
  await nextTick();
  setTimeout(async () => {
    miniMap = await initBMap('mini-map');

    navigator.geolocation.getCurrentPosition(async (pos) => {
      const { longitude, latitude } = pos.coords;
      const baiduPoint = await gpsToBaidu(longitude, latitude);
      miniMap.centerAndZoom(baiduPoint, 16);
      form.value.lng = baiduPoint.lng;
      form.value.lat = baiduPoint.lat;
      drawMiniCircle();
    }, () => {
      const p = new BMapGL.Point(116.404, 39.915);
      miniMap.centerAndZoom(p, 16);
      form.value.lng = 116.404;
      form.value.lat = 39.915;
      drawMiniCircle();
    });
  }, 300); // 延迟 300ms，确保 DOM 完成渲染
};

const onDialogClosed = () => {
  if (miniMap) miniMap.clearOverlays()
}
const onSearchSelect = ({ lng, lat }) => {
  form.value.lng = lng
  form.value.lat = lat
  nextTick(() => miniMap.panTo(new BMapGL.Point(lng, lat)))
}

// 拉取列表
const loadList = async () => {
  if (!currentElderlyId.value) return
  try {
    const res = await getFencesByElderly(currentElderlyId.value)
    fences.value = res || []
  } catch (e) {
    fences.value = []
    ElMessage.error('获取围栏列表失败')
  }
}

const del = async (id) => {
  await deleteFence(id)
  ElMessage.success('已删除')
  loadList()
}

const submit = async () => {
  const user = JSON.parse(localStorage.getItem('user') || '{}');
  if (!user.userId && !user.id) {
    ElMessage.error('请先登录');
    return;
  }
  // 使用本地引用
  if (!localElderlyId.value) {
    ElMessage.error('请先选择老人用户');
    return;
  }
  const payload = {
    familyUserId: familyUserId.value,
    elderlyUserId: localElderlyId.value,
    fenceName: form.value.fenceName,
    centerLongitude: Number(form.value.lng),
    centerLatitude: Number(form.value.lat),
    radius: Number(form.value.radius),
    status: 1
  };

  console.log('实际发送的 payload', payload);

  try {
    await axios.post(`${BASE_URL}/api/v1/family_user/fence/add`, payload, {
      headers: { 'Content-Type': 'application/json' }
    });
    ElMessage.success('围栏创建成功');
    showForm.value = false;
    loadList();
  } catch (err) {
    console.error(err);
    ElMessage.error(err.response?.data?.msg || '保存失败');
  }
}

const drawMiniCircle = () => {
  if (!miniMap) return;
  if (miniCircle) miniMap.removeOverlay(miniCircle);
  const center = new BMapGL.Point(form.value.lng, form.value.lat);
  miniCircle = new BMapGL.Circle(center, form.value.radius, {
    strokeColor: '#f56c6c',
    fillColor: '#f56c6c22'
  });
  miniMap.addOverlay(miniCircle);
  miniMap.panTo(center);
}

/* 监听 elderlyUserId 变化/首次加载 */
watch(() => currentElderlyId?.value, (newVal) => {
  if (newVal) {
    localElderlyId.value = newVal
    loadList()
  }
}, { immediate: true })

watch(() => form.value.radius, drawMiniCircle)

watch(() => localElderlyId.value, loadList, { immediate: true })
// 挂载后自动拉一次
onMounted(() => {
  loadBMap()
  loadList()
})
</script>

<style scoped>
.fence-item {
  margin: 10px 0;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 6px;
}
</style>